package demo.jwt;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

public  class JwtTokenInterceptor implements HandlerInterceptor {
	
	 @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{


	        // String token = request.getHeader("token");
	        String token = request.getParameter("token");
	        System.out.println("token="+token);

	        Map<String,Object> map = JwtUtil.parseToken(token);
	        
	        System.out.println("tokenmap="+map);
       
	        
	        if(map==null){
	        	// response.getWriter().println("token blank");
	        	request.setAttribute("error_msg", "token blank");
	        	request.getRequestDispatcher("/commerror").forward(request, response);
	        	return false;
	        }
	        
	        
	        Date expiresAt = (Date)map.get("expiresAt");
	        if(expiresAt.getTime() < System.currentTimeMillis()){
	        	// response.getWriter().println("token expired");
	        	
	        	request.setAttribute("error_msg", "token expired");
	        	request.getRequestDispatcher("/commerror").forward(request, response);
	        	return false;
	        }
	        
	     


	        return true;

	    }
	
}